<template>
  <div class="project-dataset">
    <div class="detaset-name">
      <!-- <li class="dataset-item" :class="{'active': activeIndex === index}" v-for="(item, index) in dataSetList" :key="index" @click="selDataSetItem(index)">{{item.name}}</li> -->
      <h4 class="title">数据集</h4>
      <div class="detaset-name-list">
        <el-popover
          v-for="(item, index) in dataSetList" :key="index"
          placement="top-start"
          width="200"
          trigger="hover">
          <div class="dataset-item-desc">
            {{item.profile}}
          </div>
          <a class="dataset-item" :class="{'active': activeIndex === index}" @click="selDataSetItem(index)" slot="reference">{{item.name}}</a>
        </el-popover>
      </div>
    </div>
    <div class="file-box">
      <div class="filepath-header">
        <img class="file-icon" src="@/common/image/icon/folder.png">
        <div class="breadcrumb">
          <span class="file-path">{{filePath}}</span>
        </div>
      </div>
      <div class="file-table">
        <el-table
          :data="fileList"
          style="width: 100%"
          :header-row-class-name="handleTableHeaderclass">
          <el-table-column>
            <!-- label="文件/文件夹名称"> -->
            <template slot="header" slot-scope="slot">
                <a class="table-head">
                  <i class="head-icon">{{slot}}</i>
                  <span class="head-txt">文件/文件夹名称</span>
                </a>
            </template>
            <template slot-scope="scope">
              <div class="table-link">
                <i :class="{'file-pic': scope.row.isImg, 'file-icon': !scope.row.directory && !scope.row.isImg, 'folder-icon': scope.row.directory}"></i>
                <span>{{ scope.row.fileName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="updateTime"
            label="修改日期"
            width="230">
            <template slot-scope="scope">
              <span>{{ new Date(scope.row.updateTime).Format("yyyy-MM-dd hh:mm:ss") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="size"
            label="大小"
            width="188">
            <template slot-scope="scope">
              <span>{{ scope.row.size ? scope.row.size : '--' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="markdown-box" v-if="showMarkdown">
      <div class="header-markdown">
        <span class="header-left"><img src="@/common/image/icon/book-open-variant.png">README.md</span>
        <span v-if="!editMarkdown && curDataSetItem.type !== 1" class="header-right" @click="doEditMarkdown"><i class="el-icon-edit-outline"></i>编辑</span>
        <span v-else-if="editMarkdown" class="header-right"><i class="icon-save" /><span @click="doSaveMarkdown">保存</span><i class="icon-cancle" /><span @click="doCancleMarkdown">取消</span></span>
      </div>
      <viewer
        v-show="!editMarkdown"
        :value="markdownData"
        height="500px"
        class="markdown-content"
      />
      <editor
        v-show="editMarkdown"
        ref="tuiEditor"
        v-model="markdownData"
        :options="editorOptions"
        previewStyle="vertical"
        height="500px"
      />
    </div>
  </div>
</template>

<script>
import 'tui-editor/dist/tui-editor.css'
import 'tui-editor/dist/tui-editor-contents.css'
import 'codemirror/lib/codemirror.css'
import { Editor, Viewer } from '@toast-ui/vue-editor'

import axios from 'axios'
import { mapGetters } from 'vuex'
import { getProjectDataSetList } from '@/api/dataset'
import { apiGetFileList, getPublicDatasetFileList } from '@/api/filecenter'
export default {
  components: {
    'editor': Editor,
    'viewer': Viewer
  },
  data () {
    return {
      activeIndex: 0,
      dataSetList: [],
      fileList: [],
      filePath: '',
      // markdown文件内容
      markdownData: '',
      // 展示Markdown
      showMarkdown: false,
      // 编辑markdown
      editMarkdown: false,
      editorOptions: {
        hideModeSwitch: true
      },
      curDataSetItem: {}
    }
  },
  mounted () {
    this._getProjectDataSet()
  },
  methods: {
    selDataSetItem (index) {
      this.activeIndex = index
      this._getFileList(this.dataSetList[index])
    },
    // 编辑markdown
    doEditMarkdown () {
      this.editMarkdown = true
      this.$nextTick(() => {
        this.$refs.tuiEditor.invoke('setValue', this.markdownData)
        this.$refs.tuiEditor.invoke('scrollTop', 1)
      })
    },
    // 保存markdown
    doSaveMarkdown () {
      let blob = new Blob([this.$refs.tuiEditor.invoke('getValue')], { type: 'text/plain' })
      let fd = new FormData()
      fd.append('dir', `/${this.curDataSetItem.name}`)
      fd.append('type', 3)
      fd.append('name', 'README.md')
      fd.append('file', blob, 'README.md')
      let url = `/gateway/fileCenter/api/file/upload`
      axios({
        method: 'post',
        url: url,
        data: fd
      }).then(res => {
        this.$message({ message: '保存成功', showClose: true, type: 'success' })
        this.editMarkdown = false
        this._getFileContent()
      })
    },
    // 取消编辑markdown
    doCancleMarkdown () {
      this.editMarkdown = false
    },
    handleTableHeaderclass () {
      return 'table-head-th'
    },
    _getProjectDataSet () {
      // const query = `?projectId=${this.curProject.id}`
      const query = `?projectId=${this.$route.query.id}`
      getProjectDataSetList(query).then(res => {
        if (res.message.code === 0) {
          this.dataSetList = res.data
          // 默认查询第一条数据集文件结构
          if (this.dataSetList.length > 0) {
            this._getFileList(this.dataSetList[0])
          }
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 查询文件列表(数据集结构)
    _getFileList (item) {
      this.curDataSetItem = item
      let apiMethod = ''
      let para = ''
      if (item.username) {
        this.filePath = '/data/' + item.username + '/' + item.name
      } else {
        this.filePath = '/data/' + item.name
      }
      if (item.type === 1) {
        apiMethod = getPublicDatasetFileList
        para = `?number=${item.number}`
      } else {
        apiMethod = apiGetFileList
        const path = item.path.split(item.userId)[1]
        para = `?type=3&dir=${path}&pageNumber=1&pageSize=20`
      }
      apiMethod(para).then(res => {
        if (res.message.code === 0) {
          this.totalPage = res.data.totalCount
          this.fileList = res.data.fileList
          // 判断是否是图片
          let imgExt = ['.png', '.jpg', '.jpeg', '.bmp', '.gif']
          this.fileList.forEach(el => {
            let isImg = imgExt.contain(el.fileName.extension())
            el.isImg = isImg
            if (el.fileName.toUpperCase() === 'README.MD') {
              this.showMarkdown = true
              this._getFileContent()
            }
          })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 下载Markdown内容
    _getFileContent () {
      let fileUrl = ''
      if (this.curDataSetItem.type === 1) {
        fileUrl = `/gateway/fileCenter/api/file/publicDatasetFile/preview?number=${this.curDataSetItem.number}&path=/README.md`
      } else {
        fileUrl = `/gateway/fileCenter/api/file/preview?type=3&path=/${this.curDataSetItem.name}/README.md`
      }
      axios({
        method: 'get',
        url: fileUrl
      }).then(res => {
        if (res.data === '') {
          this.showMarkdown = false
        } else {
          this.showMarkdown = true
          this.markdownData = res.data
        }
      })
    }
  },
  computed: {
    ...mapGetters([
      'curProject'
    ])
  }
}
</script>

<style lang="stylus" scoped>
@import "../../common/stylus/mixin"
.project-dataset
  background #ffffff
  .detaset-name
    display flex
    .title
      flex 0 0 50px
      height 28px
      line-height 28px
      font-size 14px
      color #676767
  .no-data
    display flex
    align-items center
    justify-content center
  .detaset-name-list
    flex 1
    font-size 0
    .dataset-item
      display inline-block
      padding 0 10px
      margin-left 12px
      height 28px
      line-height 26px
      border 1px solid #DCDFE6
      border-radius 3px
      font-size 14px
      color #2D323B
      text-decoration none
    .active
      color #2196F3
      border 1px solid #A3D0FD
  .filepath-header
    height 20px
    line-height 1.5
    display flex
    align-items center
    // padding-left 10px
    margin 20px 0 20px
    .file-icon
      width 16px
      height 16px
      display inline-block
    .breadcrumb
      display inline-block
      font-weight 600
      font-size 14px
      color #2D323B
      padding-left 10px
      .file-path
        cursor not-allowed
        color #2D323B
        font-size 14px
        &:hover
          color: $color-lan
  .file-table
    .table-head
      padding-left 14px
      .head-icon
        model(16px,16px,0 11px 0 0)
        background-image url('../../common/image/icon/folder.png')
        background-size 16px 16px
        display inline-block
        vertical-align middle
        font-size 0
      .head-txt
        font-size 14px
        color #4A4A4A
    .table-link
      padding-left 14px
      cursor not-allowed
      >span
        color #409eff
        &:hover
          color: $color-lan
      .file-icon
        model(16px,16px,0 11px 0 0)
        background-image url('../../common/image/icon/file.png')
        background-size 16px 16px
        display inline-block
        vertical-align middle
      .folder-icon
        model(16px,16px,0 11px 0 0)
        background-image url('../../common/image/icon/folder.png')
        background-size 16px 16px
        display inline-block
        vertical-align middle
      .file-pic
          model(16px,16px,0 11px 0 0)
          background-image url('../../common/image/icon/folder.png')
          background-size 16px 16px
          display inline-block
          vertical-align middle
  .markdown-box
    border 1px solid #ebeef5
    margin-top 20px
    .header-markdown
      display flex
      justify-content space-between
      font-size 12px
      border-bottom 1px solid #ebeef5
      padding 10px 20px
      .header-left
        display flex
        align-items center
        height 20px
        line-height 20px
        >img
          width 16px
          height 16px
          margin-right 5px
      .header-right
        display flex
        align-items center
        height 20px
        line-height 20px
        cursor pointer
        >i
          margin-right 5px
        .icon-save
          display inline-block
          width 12px
          height 12px
          margin-right 3px
          background url('../../common/image/icon/save.png')
          background-size 12px 12px
        .icon-cancle
          display inline-block
          margin-left 10px
          width 12px
          height 12px
          margin-right 3px
          background url('../../common/image/icon/edit-cancle.png')
          background-size 12px 12px
    .markdown-content
      padding 20px
.dataset-item-desc
  word-wrap break-word
  word-break normal
</style>
